package cn.jtfadmin.base.lang.config.excel;

import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import cn.jtfadmin.base.lang.config.ApplicationHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * easypoi 中的验证处理器,
 * 使用位置：导入excel 时 jsr 303 验证对象
 *
 * @author jtf
 * @see cn.afterturn.easypoi.excel.entity.ImportParams#setVerifyHandler(IExcelVerifyHandler)
 * @since 0.0.1
 */
@Component
public class ExcelVerifyHandler implements IExcelVerifyHandler {




    @Override
    public ExcelVerifyHandlerResult verifyHandler(Object obj) {
        Validator bean = ApplicationHolder.getApplicationContext()
                .getBean(Validator.class);
        Set<ConstraintViolation<Object>> validate = bean.validate(obj);
        ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult();
        if (CollectionUtils.isEmpty(validate)) {
            result.setSuccess(true);
            result.setMsg("成功");
        } else {
            result.setSuccess(false);
            result.setMsg(validate.stream().map(t -> t.getMessage()).collect(Collectors.joining(System.lineSeparator())));
        }
        return result;
    }
}
